<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="openForm.agentType === 'agent' ? '新建企业代理':'新建兼职'" custom-class="mydialog"
             width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="代理类型" prop="agentType">
            <el-radio-group v-model="openForm.agentType">
              <el-radio label="agent">企业代理</el-radio>
              <el-radio label="agent_person">兼职大包</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="openForm.agentType === 'agent'" gutter="40">
        <el-col :span="12">
          <el-form-item label="代理商名称" prop="agentName">
            <el-input v-model="openForm.agentName" clearable placeholder="请输入代理商名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在地区" prop="value">
            <el-cascader v-model="openForm.value" :options="cityList" :popper-append-to-body="false" :props="{ value:'regionCode',label:'regionName',expandTrigger: 'hover' }"
                         placeholder="请选择地区" style="width:100%"
                         @change="handlCity"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="userName">
            <el-input v-model="openForm.userName" clearable placeholder="请输入联系人"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="creditCode">
            <el-input v-model="openForm.creditCode" clearable placeholder="请输入统一社会信用代码"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="openForm.agentType === 'agent_person'" gutter="40">
        <el-col :span="12">
          <el-form-item label="兼职人员姓名" prop="userName">
            <el-input v-model="openForm.userName" clearable placeholder="请输入兼职人员姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="openForm.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证" prop="cardNumber">
            <el-input v-model="openForm.cardNumber" clearable placeholder="请输入身份证号码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="身份证附件" prop="cardFiles">
            <div class="qualityFiles-container">
              <div v-for="(item,index) in openForm.cardFiles" :key="index" class="file-item">
                <image-upload-view ref="imageUploadView" :data="item"/>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, nextTick, reactive, ref, toRefs,} from "vue";
import area from "@/utils/area";
import {validateVETel} from "@/utils/validate";
import {crmStore} from "@CRM/store";

export default {
  props:{
    clueId:{
      type:Number,
      default:0
    }
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机码"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateName = async (rule, value, callback) => {
      if (value === "") {
        callback("请输入代理商名称");
      } else {
        const aaa = await validateVEName(value);
        if (aaa) {
          callback(new Error("代理商名称已存在"));
        } else {
          callback();
        }
      }
    };
    const validateIdCard = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback();
      } else {
        if (validateVEIdCard(value)) {
          callback(new Error("格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateUserName = (rule, value, callback) => {
      if (data.openForm.agentType === "agent") {
        if (value === "") {
          callback(new Error("请输入联系人"));
        } else {
          callback();
        }
      } else {
        if (value === "") {
          callback(new Error("请输入兼职姓名"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    var data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        value: null,
        agentNumber: "",
        agentName: "", // 代理商名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        sex: "1",
        cardNumber: "",
        cardFiles:
            JSON.parse(
                JSON.stringify(
                    crmStore.getters["jsonData/getJsonData"][
                        "part_person_qualification"
                        ].data
                )
            ) || [],
        agentType: 'agent',
      },
      openRef: null,
      rules: {
        agentName: [
          {required: true, validator: validateName, trigger: "blur"},
        ],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"},
        ],
        userName: [
          {required: true, validator: validateUserName, trigger: "blur"},
        ],
        tel: [{required: true, validator: validateTel, trigger: "blur"}],
        value: [{required: true, message: "请选择地区", trigger: "change"}],
        creditCode: [
          {required: true, message: "请输入统一社会信用代码", trigger: "blur"},
        ],
        cardNumber: [{validator: validateIdCard, trigger: "blur"}],
      },
      num: 0,
    });
    const currentInstance = getCurrentInstance();

    const handlCity = (val) => {
      if (val) {
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
        nextTick((_) => {
          data.openRef.clearValidate("provinceCode");
        });
      }
    };

    const validateVEName = async (val) => {
      const paramData = {
        table: "agent",
        column: "agent_name",
        column_data: val,
        id: data.openForm.id ? data.openForm.id : "",
      };
      const booleName = ref(false);
      const res = await api.channelAgent.POTENTIALAGENT_NAME(paramData);
      if (res.code === 0) {
        if (res.data.exist === "1") {
          booleName.value = true;
        } else {
          booleName.value = false;
        }
      } else {
        booleName.value = false;
      }
      return booleName.value;
    };

    const close = () => {
      data.openBoole = false;
      handlRemove();
    };

    const handlRemove = () => {
      data.openForm.provinceCode = "";
      data.openForm.cityCode = "";
      data.openForm.areaCode = "";
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val, num,obj) => {
      data.openBoole = true;
      if (val) {
        for (const key in data.openForm) {
          data.openForm[key] = val[key];
        }
        data.openForm.id = val.id;
        data.openForm.value = [
          data.openForm.provinceCode,
          data.openForm.cityCode,
          data.openForm.areaCode,
        ];
      }
      if (num) {
        data.num = num;
      }

      if (obj){
        console.log(obj)
        data.openForm.value = [obj.provinceCode,obj.cityCode,obj.areaCode]
        data.openForm.address = obj.address
        data.openForm.tel = obj.contactPhone
        data.openForm.userName = obj.contactName
        data.openForm.agentName = obj.company
      }
    };

    // 确定
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const commit = ref(undefined);
          const msgs = ref("");
          if (data.openForm.id) {
            if (data.num === 1) {
              commit.value = api.channelAgent.POTENTIALAGENT_CHANGE;
              msgs.value = "变更成功";
              dataobj.id = data.openForm.id;
            }
            if (data.num === 2) {
              commit.value = api.channelAgent.POTENTIALAGENT_UPDATE;
              msgs.value = "编辑成功";
              dataobj.id = data.openForm.id;
            }
          } else {
            commit.value = api.channelAgent.POTENTIALAGENT_CREATE;
            msgs.value = "创建成功";
          }
          commit.value(data.openForm,props.clueId).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msgs.value,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCity,
      handlRemove,
      validateVEName,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>
